package io.finer.erp.jeecg.bas.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.util.ali.WuliuUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMeasureUnit;
import io.finer.erp.jeecg.bas.entity.ZrkDeliver;
import io.finer.erp.jeecg.bas.entity.ZrkDeliverEntry;
import io.finer.erp.jeecg.bas.entity.ZrkDriver;
import io.finer.erp.jeecg.bas.entity.ZrkExpress;
import io.finer.erp.jeecg.bas.entity.ZrkExpressEntry;
import io.finer.erp.jeecg.bas.entity.ZrkExpressProcess;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasMeasureUnitService;
import io.finer.erp.jeecg.bas.service.IZrkDeliverEntryService;
import io.finer.erp.jeecg.bas.service.IZrkDeliverService;
import io.finer.erp.jeecg.bas.service.IZrkDriverService;
import io.finer.erp.jeecg.bas.service.IZrkExpressEntryService;
import io.finer.erp.jeecg.bas.service.IZrkExpressProcessService;
import io.finer.erp.jeecg.bas.service.IZrkExpressService;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 商城订单物流信息表
 * @Author: jeecg-boot
 * @Date:   2020-08-27
 * @Version: V1.0
 */
@Api(tags="商城订单物流信息表")
@RestController
@RequestMapping("/bas/zrkExpress")
@Slf4j
public class ZrkExpressController extends JeecgController<ZrkExpress, IZrkExpressService> {

	@Autowired
	private IZrkExpressService zrkExpressService;

	@Autowired
	private IZrkExpressEntryService zrkExpressEntryService;

	@Autowired
	private IZrkDriverService zrkDriverService;

	@Autowired
	private IBasMaterialService basMaterialService;

	@Autowired
	private IZrkDeliverService zrkDeliverService;

	@Autowired
	private IZrkExpressProcessService zrkExpressProcessService;

	@Autowired
	private IZrkDeliverEntryService zrkDeliverEntryService;

	@Autowired
	private IBasMeasureUnitService basMeasureUnitService;

	@Autowired
	private IBasMaterialCategoryService basMaterialCategoryService;

	@Autowired
	private IStkIoBillService stkIoBillService;

	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param zrkExpress
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "商城订单物流信息表-分页列表查询")
	@ApiOperation(value="商城订单物流信息表-分页列表查询", notes="商城订单物流信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ZrkExpress zrkExpress,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		QueryWrapper<ZrkExpress> queryWrapper = QueryGenerator.initQueryWrapper(zrkExpress, req.getParameterMap());
		Page<ZrkExpress> page = new Page<ZrkExpress>(pageNo, pageSize);
		IPage<ZrkExpress> pageList = zrkExpressService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	@AutoLog(value = "商城订单物流信息表-发车-手动添加状态-查询")
	@ApiOperation(value="商城订单物流信息表-发车-手动添加状态-查询", notes="商城订单物流信息表-发车-手动添加状态-查询")
	@PostMapping(value = "/shopOder")
	public Result<?> addManually(@RequestBody ZrkExpress shopOder) {
		List<Map<String, Object>> resultList = new ArrayList<>();
		//根据商城订单号查询物流信息
		Map<String,Object> columnMap=new HashMap<String,Object>();
		columnMap.put("shop_order", shopOder.getShopOrder());
		Collection<ZrkExpress> collection=zrkExpressService.listByMap(columnMap);
		if(null!=collection&&collection.size()>0) {
			Iterator<ZrkExpress> iterator=collection.iterator();
			while(iterator.hasNext()) {
				Map<String, Object> map = new HashMap<String, Object>();
				ZrkExpress z = iterator.next();
				map.put("express", z);
				//根据物流编号查询物流状态
				LambdaQueryWrapper<ZrkExpressProcess> query = new LambdaQueryWrapper<>();
				query.eq(ZrkExpressProcess::getExpressId, z.getId());
				List<ZrkExpressProcess> list = zrkExpressProcessService.list(query);
				map.put("list", list);
				resultList.add(map);

			}
		}
		return Result.ok(resultList);
	}

	/**
	 *   PDA扫码-添加物流信息
	 * @param zrkExpress
	 * @return
	 */
	@AutoLog(value = "PDA扫码-添加物流信息")
	@ApiOperation(value="PDA扫码-添加物流信息", notes="PDA扫码-添加物流信息")
	@PostMapping(value = "/pdaAdd")
	public Result<?> pdaAdd(@RequestBody ZrkExpress zrkExpress) {
		zrkExpress.setIsPerson(2);//是否手动更新
		zrkExpress.setExpressType("2");//货运方式设置为物流
		//查询出货单信息(根据出货单号)
		QueryWrapper<ZrkDeliver> zdQw=new QueryWrapper<ZrkDeliver>();
		zdQw.eq("deliver_code", zrkExpress.getBillNo());
		ZrkDeliver zd=zrkDeliverService.getOne(zdQw.last("LIMIT 1"));
		StkIoBill stkIoBill=null;
		if(null!=zd) {
			//根据销售单号查询商城订单号
			QueryWrapper<StkIoBill> queryWrapper=new QueryWrapper<StkIoBill>();
			queryWrapper.eq("bill_no", zd.getBillNo());
			stkIoBill=stkIoBillService.getOne(queryWrapper.last("LIMIT 1"));
		}else {
			return Result.error("未查询到出货单");
		}
		if(null!=stkIoBill) {
			zrkExpress.setShopOrder(stkIoBill.getSourceNo());//设置商城订单号
		}else {
			return Result.error("未找到销售出库单");
		}
		//添加物流信息时判断发货方式，当发货方式为1也即：发车时 修改物流联系方式为司机手机号
		if(zrkExpress.getExpressName().equals("1")) {
			//查询司机信息
			ZrkDriver zrkDriver=zrkDriverService.getById(zrkExpress.getDriverId());
			zrkExpress.setExpressMobile(zrkDriver.getDriverMobile());
		}
		//判断物流名称从而选择发货方式
		if(zrkExpress.getExpressName().equals("1")) {
			//发货方式为发车
			zrkExpress.setExpressType("1");
		}else {
			//发货方式为物流
			zrkExpress.setExpressType("2");
		}
		//添加到数据库
//		zrkExpressService.save(zrkExpress);
		//物流信息添加完成后通过关联的销售出库单去查询出货单信息
		QueryWrapper<ZrkDeliver> zrQW=new QueryWrapper<ZrkDeliver>();
		zrQW.eq("deliver_code", zrkExpress.getBillNo());
		//根据出库单号查询出货单信息
		Collection<ZrkDeliver> collection=zrkDeliverService.list(zrQW);
		if(null!=collection&&collection.size()>0) {
			Iterator<ZrkDeliver> iterator=collection.iterator();
			while(iterator.hasNext()) {
				ZrkDeliver zrkDeliver=iterator.next();
				if(zrkDeliver.getIsExpress()==0) {
					zrkExpressService.save(zrkExpress);
					QueryWrapper<ZrkDeliverEntry> qw=new QueryWrapper<ZrkDeliverEntry>();
					qw.eq("deliver_id", zrkDeliver.getId());
					List<ZrkDeliverEntry> zdeList=zrkDeliverEntryService.list(qw);
					//计算司机出货量、出车量
					reCalNew(zdeList,zrkExpress);
					//将出货单状态修改为已统计
					zrkDeliver.setIsExpress(1);
					zrkDeliverService.updateById(zrkDeliver);//数据库更新状态
				}else {
					return Result.error("已发物流,不允许重复操作");
				}
			}
		}
		return Result.ok("添加成功！");
	}

	@AutoLog(value = "商城订单物流信息表-物流查询")
	@ApiOperation(value="商城订单物流信息表-物流查询", notes="商城订单物流信息表-物流查询")
	@PostMapping(value = "/viewLogistics")
	public Result<?> getWuLiu(@RequestParam(name="no") String no,@RequestParam(name="type") String type) {
		//根据物流号和物流公司编号查询物流实时状态
		List<Map<String, String>> resultList = WuliuUtil.getWuliu(no, type);
		//根据物流编号查询物流状态表中数据
		QueryWrapper<ZrkExpressProcess> qw = new QueryWrapper<>();
		qw.eq("express_id", no);
		List<ZrkExpressProcess> zrkExpressProcessList = zrkExpressProcessService.list(qw);
		System.err.println(zrkExpressProcessList);
		if(null!=zrkExpressProcessList) {
			//将查到的物流状态信息保存到新的list集合中
			List<String> strList = new ArrayList<>();
			for(ZrkExpressProcess zeProcess:zrkExpressProcessList) {
				String epContent = zeProcess.getExpressContent();
				strList.add(epContent);
			}
			for(Map<String, String> map:resultList) {
				String expressContent = map.get("status");
				//判断查到的物流状态信息是否已保存到了物流状态表中，
				//将以保存的数据筛出，确保保存的是新的数据
				if(!strList.contains(expressContent)) {
					ZrkExpressProcess zrkExpressProcess = new ZrkExpressProcess();
					zrkExpressProcess.setExpressId(no);
					zrkExpressProcess.setExpressContent(expressContent);
					//判断物流状态信息中是否有“签收”，将物流状态表中的物流状态是改为运输中，还是已签收（1-运输中，2-签收）
					if(expressContent.contains("签收")) {
						zrkExpressProcess.setExpressStatus("2");
					}else {
						zrkExpressProcess.setExpressStatus("1");
					}
					zrkExpressProcessService.save(zrkExpressProcess);
				}
			}			
		}
		return Result.ok(resultList);
	}
	
	/**
	 *   添加
	 * @param zrkExpress
	 * @return
	 */
	@AutoLog(value = "商城订单物流信息表-添加")
	@ApiOperation(value="商城订单物流信息表-添加", notes="商城订单物流信息表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ZrkExpress zrkExpress) {
		//添加物流信息时判断发货方式，当发货方式为1也即：发车时 修改物流联系方式为司机手机号
		if(zrkExpress.getExpressName().equals("1")) {
			//查询司机信息
			ZrkDriver zrkDriver=zrkDriverService.getById(zrkExpress.getDriverId());
			zrkExpress.setExpressMobile(zrkDriver.getDriverMobile());
		}
		//判断物流名称从而选择发货方式
		if(zrkExpress.getExpressName().equals("1")) {
			//发货方式为发车
			zrkExpress.setExpressType("1");
		}else {
			//发货方式为物流
			zrkExpress.setExpressType("2");
		}
		//物流信息添加完成后通过关联的销售出库单去查询出货单信息
		QueryWrapper<ZrkDeliver> zrQW=new QueryWrapper<ZrkDeliver>();
		zrQW.eq("deliver_code", zrkExpress.getBillNo());
		//根据出库单号查询出货单信息
		Collection<ZrkDeliver> collection=zrkDeliverService.list(zrQW);
		if(null!=collection&&collection.size()>0) {
			Iterator<ZrkDeliver> iterator=collection.iterator();
			while(iterator.hasNext()) {
				ZrkDeliver zrkDeliver=iterator.next();
				if(zrkDeliver.getIsExpress()==0) {
					zrkExpressService.save(zrkExpress);//未发物流
					//添加物流车辆运送明细信息
					//					ZrkExpressEntry zrkExpressEntry=new ZrkExpressEntry();
					//					zrkExpressEntry.setCreateBy("admin");
					//					zrkExpressEntry.setCreateTime(DateUtils.getDate());
					//					zrkExpressEntry.setEntryId(zrkExpress.getId());
					//					zrkExpressEntry.setIsCal(0);
					//					zrkExpressEntry.setMaterialId(zrkDeliver.getMaterialId());
					//					zrkExpressEntry.setUnitId(zrkDeliver.getUnitId());
					//					zrkExpressEntry.setZrkCount(zrkDeliver.getMaterialAmt());
					//					//设置产品件数
					//					zrkExpressEntry.setExpressJs(Integer.parseInt(zrkDeliver.getMaterialJs()));
					//					zrkExpressEntryService.save(zrkExpressEntry);
					QueryWrapper<ZrkDeliverEntry> qw=new QueryWrapper<ZrkDeliverEntry>();
					qw.eq("deliver_id", zrkDeliver.getId());
					List<ZrkDeliverEntry> zdeList=zrkDeliverEntryService.list(qw);
					//计算司机出货量、出车量
					reCalNew(zdeList,zrkExpress);
					//将出货单状态修改为已统计
					zrkDeliver.setIsExpress(1);
					zrkDeliverService.updateById(zrkDeliver);//数据库更新状态
				}else {
					return Result.error("已发物流,不允许重复操作");
				}
			}
		}
		return Result.ok("添加成功！");
	}

	private void reCalNew(List<ZrkDeliverEntry> zdeList,ZrkExpress zrkExpress) {
		if(null!=zdeList&&zdeList.size()>0) {
			//查询司机信息
			ZrkDriver zrkDriver=zrkDriverService.getById(zrkExpress.getDriverId());
			BigDecimal totalSquare=BigDecimal.ZERO;
			for(ZrkDeliverEntry zde:zdeList) {
				if(zde.getIsCal()==0) {
					zde.setIsCal(1);
					zrkDeliverEntryService.updateById(zde);//将物流明细设置为已计算
					BigDecimal qtyAmt=BigDecimal.ZERO;
					BigDecimal materialCount=BigDecimal.ZERO;
					//计算货物金额
					BasMaterial basMaterial=basMaterialService.getById(zde.getMaterialId());
					try {
						materialCount=zde.getMaterialCount()==null?BigDecimal.ZERO:zde.getMaterialCount();
						BasMeasureUnit unit=basMeasureUnitService.getById(zde.getUnitId());
						qtyAmt=zrkExpress.getQtyAmt()==null?BigDecimal.ZERO:zrkExpress.getQtyAmt();
						//读取出货单中产品件数
						int js=zrkExpress.getExpressAmt()==null?0:zrkExpress.getExpressAmt();
						zrkExpress.setExpressAmt(js+1);//计算货物件数
						//						BasMeasureUnit unit=basMeasureUnitService.getById(basMaterial.getUnitId());
						//						BigDecimal tt=BigDecimal.ZERO;//货物价格
						BigDecimal materialAmt=zrkExpress.getMaterialAmt()==null?BigDecimal.ZERO:zrkExpress.getMaterialAmt();
						BigDecimal salPrice=basMaterial.getSalePrice()==null?BigDecimal.ZERO:basMaterial.getSalePrice();
						/************货物价格计算因为是直接读取的物料信息所以物流明细与物料的计量单位是一样的*********/
						//货物价格计算
						BigDecimal tmp=salPrice.multiply(materialCount);
						//加上之前的
						BigDecimal tm=materialAmt.add(tmp);
						zrkExpress.setMaterialAmt(tm);
						/************货物价格计算因为是直接读取的物料信息所以物流明细与物料的计量单位是一样的*********/
						if(unit.getName().indexOf("吨")>0) {
							//判断是否需要更新司机载货量
							if(null!=zrkDriver) {
								//司机载货量
								zrkDriver.setDriverChcount(zrkDriver.getDriverChcount().add(zde.getMaterialCount()));
							}
							//计算载货量（吨）
							zrkExpress.setQtyAmt(qtyAmt.add(materialCount));
							//吨转平方
							BigDecimal tonToSquare=basMaterialCategoryService.getSquare(materialCount, basMaterial.getCategoryId());
							totalSquare=totalSquare.add(tonToSquare);
						}else {
							//平方转吨
							BigDecimal squareToTon=basMaterialCategoryService.getTon(zde.getMaterialCount(), basMaterial.getCategoryId());
							if(null!=zrkDriver) {
								zrkDriver.setDriverChcount(zrkDriver.getDriverChcount().add(squareToTon));
							}
							//计算载货量（吨）
							zrkExpress.setQtyAmt(qtyAmt.add(squareToTon));
							totalSquare=totalSquare.add(materialCount);
						}
						//						materialCount=zde.getMaterialCount();//载货量（吨）
					} catch (Exception e) {
					}
				}
			}
			BigDecimal perMoney=BigDecimal.ZERO;
			//计算每平方运费,非零检测
			if(totalSquare.compareTo(BigDecimal.ZERO)>0) {
				perMoney=zrkExpress.getExpressMoney().divide(totalSquare, 4, BigDecimal.ROUND_CEILING);
			}
			zrkExpress.setPerSquareMoney(perMoney);
			zrkExpressService.updateById(zrkExpress);
		}
	}

	private void reCal(ZrkExpressEntry zrkExpressEntry) {
		zrkExpressEntry=zrkExpressEntryService.getById(zrkExpressEntry.getId());
		//运送物料明细添加完成后马上统计该司机的出货量、出车次数
		ZrkExpress zrkExpress=zrkExpressService.getById(zrkExpressEntry.getEntryId());//查询主表信息
		//查询司机信息
		ZrkDriver zrkDriver=zrkDriverService.getById(zrkExpress.getDriverId());
		//计算该司机出货量
		if(zrkExpressEntry.getIsCal().intValue()==0) {
			zrkDriver.setDriverChcount(zrkDriver.getDriverChcount().add(zrkExpressEntry.getZrkCount()));
			zrkExpressEntry.setIsCal(1);
			//计算吨位(可能存在吨转平方的情况，此处因为没有吨转平方的公式所以暂时未做处理)
			BigDecimal qtyAmt=zrkExpress.getQtyAmt();
			zrkExpress.setQtyAmt(qtyAmt.add((zrkExpressEntry.getZrkCount())));
			//读取出货单中产品件数
			int js=zrkExpress.getExpressAmt();
			zrkExpress.setExpressAmt(js+zrkExpressEntry.getExpressJs());//计算货物件数
			//计算货物金额
			BasMaterial basMaterial=basMaterialService.getById(zrkExpressEntry.getMaterialId());
			BigDecimal materialAmt=zrkExpress.getMaterialAmt();
			BigDecimal salPrice=basMaterial.getSalePrice();
			BigDecimal tmp=salPrice.multiply(zrkExpressEntry.getZrkCount());
			BigDecimal tm=materialAmt.add(tmp);
			zrkExpress.setMaterialAmt(tm);//此处是以吨计算的价格，注意：后期收到吨转平方公式后要做换算后再计算
		}
		//计算该司机出车量(当ZrkExpress中is_cal为1时，代表已经给该司机增加过出车次数)
		if(zrkExpress.getIsCal().intValue()==0) {
			zrkDriver.setDriverCccount(zrkDriver.getDriverCccount()+1);
			//将ZrkExpress中isCal设置为1
			zrkExpress.setIsCal(1);
		}
		zrkExpressEntryService.updateById(zrkExpressEntry);
		zrkDriverService.updateById(zrkDriver);//更新司机出货量、出车量
		zrkExpressService.updateById(zrkExpress);
	}

	/**
	 *  编辑
	 * @param zrkExpress
	 * @return
	 */
	@AutoLog(value = "商城订单物流信息表-编辑")
	@ApiOperation(value="商城订单物流信息表-编辑", notes="商城订单物流信息表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ZrkExpress zrkExpress) {
		zrkExpressService.updateById(zrkExpress);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商城订单物流信息表-通过id删除")
	@ApiOperation(value="商城订单物流信息表-通过id删除", notes="商城订单物流信息表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		zrkExpressService.delMain(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "商城订单物流信息表-批量删除")
	@ApiOperation(value="商城订单物流信息表-批量删除", notes="商城订单物流信息表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.zrkExpressService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 导出
	 * @return
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, ZrkExpress zrkExpress) {
		return super.exportXls(request, zrkExpress, ZrkExpress.class, "商城订单物流信息表");
	}

	/**
	 * 导入
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, ZrkExpress.class);
	}
	/*---------------------------------主表处理-end-------------------------------------*/


	/*--------------------------------子表处理-车辆运送明细-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "车辆运送明细-通过主表ID查询")
	@ApiOperation(value="车辆运送明细-通过主表ID查询", notes="车辆运送明细-通过主表ID查询")
	@GetMapping(value = "/listZrkExpressEntryByMainId")
	public Result<?> listZrkExpressEntryByMainId(ZrkExpressEntry zrkExpressEntry,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			HttpServletRequest req) {
		QueryWrapper<ZrkExpressEntry> queryWrapper = QueryGenerator.initQueryWrapper(zrkExpressEntry, req.getParameterMap());
		Page<ZrkExpressEntry> page = new Page<ZrkExpressEntry>(pageNo, pageSize);
		IPage<ZrkExpressEntry> pageList = zrkExpressEntryService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
	 * 添加
	 * @param zrkExpressEntry
	 * @return
	 */
	@AutoLog(value = "车辆运送明细-添加")
	@ApiOperation(value="车辆运送明细-添加", notes="车辆运送明细-添加")
	@PostMapping(value = "/addZrkExpressEntry")
	public Result<?> addZrkExpressEntry(@RequestBody ZrkExpressEntry zrkExpressEntry) {
		zrkExpressEntryService.save(zrkExpressEntry);
		zrkExpressEntry=zrkExpressEntryService.getById(zrkExpressEntry.getId());
		//运送物料明细添加完成后马上统计该司机的出货量、出车次数
		ZrkExpress zrkExpress=zrkExpressService.getById(zrkExpressEntry.getEntryId());//查询主表信息
		//查询司机信息
		ZrkDriver zrkDriver=zrkDriverService.getById(zrkExpress.getDriverId());
		//计算该司机出货量
		if(zrkExpressEntry.getIsCal().intValue()==0) {
			zrkDriver.setDriverChcount(zrkDriver.getDriverChcount().add(zrkExpressEntry.getZrkCount()));
			zrkExpressEntry.setIsCal(1);
			//计算吨位(可能存在吨转平方的情况，此处因为没有吨转平方的公式所以暂时未做处理)
			BigDecimal qtyAmt=zrkExpress.getQtyAmt()==null?new BigDecimal("0"):zrkExpress.getQtyAmt();
			zrkExpress.setQtyAmt(qtyAmt.add((zrkExpressEntry.getZrkCount())));
			//添加一次明细代表一件货
			int js=zrkExpress.getExpressAmt()==null?0:zrkExpress.getExpressAmt();
			zrkExpress.setExpressAmt(js+1);
			//计算货物金额
			BasMaterial basMaterial=basMaterialService.getById(zrkExpressEntry.getMaterialId());
			BigDecimal materialAmt=zrkExpress.getMaterialAmt()==null?BigDecimal.ZERO:zrkExpress.getMaterialAmt();
			BigDecimal salPrice=basMaterial.getSalePrice()==null?BigDecimal.ZERO:basMaterial.getSalePrice();
			zrkExpress.setMaterialAmt(materialAmt.add(salPrice.multiply(zrkExpressEntry.getZrkCount())));//此处是以吨计算的价格，注意：后期收到吨转平方公式后要做换算后再计算
		}
		//计算该司机出车量(当ZrkExpress中is_cal为1时，代表已经给该司机增加过出车次数)
		if(zrkExpress.getIsCal().intValue()==0) {
			zrkDriver.setDriverCccount(zrkDriver.getDriverCccount()+1);
			//将ZrkExpress中isCal设置为1
			zrkExpress.setIsCal(1);
		}
		zrkExpressEntryService.updateById(zrkExpressEntry);
		zrkDriverService.updateById(zrkDriver);//更新司机出货量、出车量
		zrkExpressService.updateById(zrkExpress);
		return Result.ok("添加成功！");
	}

	/**
	 * 编辑
	 * @param zrkExpressEntry
	 * @return
	 */
	@AutoLog(value = "车辆运送明细-编辑")
	@ApiOperation(value="车辆运送明细-编辑", notes="车辆运送明细-编辑")
	@PutMapping(value = "/editZrkExpressEntry")
	public Result<?> editZrkExpressEntry(@RequestBody ZrkExpressEntry zrkExpressEntry) {
		zrkExpressEntryService.updateById(zrkExpressEntry);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "车辆运送明细-通过id删除")
	@ApiOperation(value="车辆运送明细-通过id删除", notes="车辆运送明细-通过id删除")
	@DeleteMapping(value = "/deleteZrkExpressEntry")
	public Result<?> deleteZrkExpressEntry(@RequestParam(name="id",required=true) String id) {
		zrkExpressEntryService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "车辆运送明细-批量删除")
	@ApiOperation(value="车辆运送明细-批量删除", notes="车辆运送明细-批量删除")
	@DeleteMapping(value = "/deleteBatchZrkExpressEntry")
	public Result<?> deleteBatchZrkExpressEntry(@RequestParam(name="ids",required=true) String ids) {
		this.zrkExpressEntryService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 导出
	 * @return
	 */
	@RequestMapping(value = "/exportZrkExpressEntry")
	public ModelAndView exportZrkExpressEntry(HttpServletRequest request, ZrkExpressEntry zrkExpressEntry) {
		// Step.1 组装查询条件
		QueryWrapper<ZrkExpressEntry> queryWrapper = QueryGenerator.initQueryWrapper(zrkExpressEntry, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<ZrkExpressEntry> pageList = zrkExpressEntryService.list(queryWrapper);
		List<ZrkExpressEntry> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "车辆运送明细"); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, ZrkExpressEntry.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("车辆运送明细报表", "导出人:" + sysUser.getRealname(), "车辆运送明细"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 导入
	 * @return
	 */
	@RequestMapping(value = "/importZrkExpressEntry/{mainId}")
	public Result<?> importZrkExpressEntry(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ZrkExpressEntry> list = ExcelImportUtil.importExcel(file.getInputStream(), ZrkExpressEntry.class, params);
				for (ZrkExpressEntry temp : list) {
					temp.setEntryId(mainId);
				}
				long start = System.currentTimeMillis();
				zrkExpressEntryService.saveBatch(list);
				//---------------------计算司机出货量、出车次数-------By:heckerstone------------
				//导入时批量计算司机出货量、出车量
				for(ZrkExpressEntry zrkExpressEntry:list) {
					ZrkExpress zrkExpress=zrkExpressService.getById(zrkExpressEntry.getEntryId());//查询主表信息
					//查询司机信息
					ZrkDriver zrkDriver=zrkDriverService.getById(zrkExpress.getDriverId());
					//计算该司机出货量
					if(zrkExpressEntry.getIsCal()==0||zrkExpressEntry.getIsCal()==null) {
						zrkDriver.setDriverChcount(zrkDriver.getDriverChcount().add(zrkExpressEntry.getZrkCount()));
						zrkExpressEntry.setIsCal(1);
						//计算吨位(可能存在吨转平方的情况，此处因为没有吨转平方的公式所以暂时未做处理)
						BigDecimal qtyAmt=zrkExpress.getQtyAmt()==null?new BigDecimal("0"):zrkExpress.getQtyAmt();
						zrkExpress.setQtyAmt(qtyAmt.add((zrkExpressEntry.getZrkCount())));
						//添加一次明细代表一件货
						int js=zrkExpress.getExpressAmt()==null?0:zrkExpress.getExpressAmt();
						zrkExpress.setExpressAmt(js+1);
						//计算货物金额
						BasMaterial basMaterial=basMaterialService.getById(zrkExpressEntry.getMaterialId());
						BigDecimal materialAmt=zrkExpress.getMaterialAmt()==null?BigDecimal.ZERO:zrkExpress.getMaterialAmt();
						BigDecimal salPrice=basMaterial.getSalePrice()==null?BigDecimal.ZERO:basMaterial.getSalePrice();
						zrkExpress.setMaterialAmt(materialAmt.add(salPrice.multiply(zrkExpressEntry.getZrkCount())));//此处是以吨计算的价格，注意：后期收到吨转平方公式后要做换算后再计算
					}
					//计算该司机出车量(当ZrkExpress中is_cal为1时，代表已经给该司机增加过出车次数)
					if(zrkExpress.getIsCal()==0||zrkExpress.getIsCal()==null) {
						zrkDriver.setDriverCccount(zrkDriver.getDriverCccount()+1);
						//将ZrkExpress中isCal设置为1
						zrkExpress.setIsCal(1);
					}
					zrkDriverService.updateById(zrkDriver);//更新司机出货量、出车量
					zrkExpressService.updateById(zrkExpress);
					//------------------计算司机出货量、出车次数结束-----By:heckerstone--------------
				}
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/*--------------------------------子表处理-车辆运送明细-end----------------------------------------------*/




}
